package com.hunttown.mes.manage.controller.common;

import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.user.UserTypeEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.manage.service.*;
import com.hunttown.mes.rpc.domain.query.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 大量重复可复用的代码
 * created by wangjunfu on 2019-06-16
 */
@Service
public class ModelService {
    private final static Logger logger = LoggerFactory.getLogger(ModelService.class);

    private final AnalysisManageManageService manageService;
    private final AnalysisConfigParamManageService paramService;
    private final AnalysisCatalogManageService catalogService;
    private final AnalysisManageRightRoleManageService manageRightRoleService;
    private final AnalysisRegionManageService regionService;
    private final TransportCompanyManageService companyService;
    private final TransportUserManageService userService;
    private final TransportTableChineseEnglishManageService englishService;
    private final TransportPurchaseManageService purchaseService;
    private final TransportDepartmentManageService departmentService;
    private final TransportUploadFilesManageService uploadFilesService;
    private final TransportRolesManageService rolesService;
    private final IotRegionManageService iotRegionService;
    private final IotEnterpriseManageRelService enterpriseRelService;
    private final MesEquipmentManageService mesEquipmentService;
    private final MesProductManageService mesProductService;
    private final MesProduceWorkmanshipManageService mesProduceWorkmanshipService;
    private final MesProduceWorkmanshipProcessManageService mesProduceWorkmanshipProcessService;
    private final MesProduceLineManageService mesProduceLineService;
    private final AHelpManageService helpService;
    private final Cache jedisCache;

    @Autowired
    public ModelService(AnalysisManageManageService manageService, AnalysisConfigParamManageService paramService, AnalysisCatalogManageService catalogService, AnalysisManageRightRoleManageService manageRightRoleService, AnalysisRegionManageService regionService, TransportCompanyManageService companyService, TransportUserManageService userService, TransportTableChineseEnglishManageService englishService, TransportPurchaseManageService purchaseService, TransportDepartmentManageService departmentService, TransportUploadFilesManageService uploadFilesService, TransportRolesManageService rolesService, IotRegionManageService iotRegionService, IotEnterpriseManageRelService enterpriseRelService, MesEquipmentManageService mesEquipmentService, MesProductManageService mesProductService, MesProduceWorkmanshipManageService mesProduceWorkmanshipService, MesProduceWorkmanshipProcessManageService mesProduceWorkmanshipProcessService, MesProduceLineManageService mesProduceLineService, AHelpManageService helpService, Cache jedisCache){
        this.manageService = manageService;
        this.paramService = paramService;
        this.catalogService = catalogService;
        this.manageRightRoleService = manageRightRoleService;
        this.regionService = regionService;
        this.companyService = companyService;
        this.userService = userService;
        this.englishService = englishService;
        this.purchaseService = purchaseService;
        this.departmentService = departmentService;
        this.uploadFilesService = uploadFilesService;
        this.rolesService = rolesService;
        this.iotRegionService = iotRegionService;
        this.enterpriseRelService = enterpriseRelService;
        this.mesEquipmentService = mesEquipmentService;
        this.mesProductService = mesProductService;
        this.mesProduceWorkmanshipService = mesProduceWorkmanshipService;
        this.mesProduceWorkmanshipProcessService = mesProduceWorkmanshipProcessService;
        this.mesProduceLineService = mesProduceLineService;
        this.helpService = helpService;
        this.jedisCache = jedisCache;
    }

    //region 列表工具

    /**
     * 是否开启B企业配件报销
     * 这里鱼和熊掌不可兼得，意思是：如果我报销A企业，那看不到B企业的；如果报销B企业的，那么就看不到A企业的。
     * 这里的逻辑是：
     * 1、先判断是否开启B企业报销；
     * 2、如果开启，则给ent_id赋值。
     *
     * @return 1是0否
     */
    public Boolean isOpenExpensePartsB() {
        Integer purchaseEntid = paramService.getByParamKey("open-parts-B-expense", 0);
        return purchaseEntid.equals(1);
    }

    /**
     * 获取要报销B企业的配件企业ID
     *
     * @return 企业ID
     */
    public Integer getPartsBEntId() {
        return paramService.getByParamKey("parts-B-entid", 0);
    }

    /**
     * 获取部门列表
     *
     * @param model model
     */
    public void getDepPage(Model model) {
        TransportDepartmentDTOQuery depQuery = new TransportDepartmentDTOQuery();
        depQuery.setStopFlag(0);
        depQuery.setPageSize(1000);
        Page<TransportDepartmentDTO> depPage = departmentService.getForPage(depQuery);
        model.addAttribute("depPage", depPage);
    }

    /**
     * 获取部门列表（格式化）
     *
     * @param model model
     */
    public void getDepList(Model model) {
        TransportDepartmentDTOQuery depQuery = new TransportDepartmentDTOQuery();
        depQuery.setStopFlag(0);
        depQuery.setPageSize(1000);
        Page<TransportDepartmentDTO> depPage = departmentService.getForPage(depQuery);
        List<TransportDepartmentDTO> depList = departmentService.getListByRecursion(depPage.getItems(), 0, "|");
        model.addAttribute("depList", depList);
    }

    /**
     * 获取管理员列表
     *
     * @param model model
     */
    public void getManagerPage(Model model) {

        //将List放入缓存中
        //jedisdb.hset(KeyConstants.MENU_ALL_CACHE_KEY, field, jsonobj);
        //Page<AnalysisManageDTO> page = Page.from(analysisManageDTOQuery.getPn(), analysisManageDTOQuery.getPageSize(), list);

        AnalysisManageDTOQuery manageQuery = new AnalysisManageDTOQuery();
        manageQuery.setStopFlag(0);
        manageQuery.setPageSize(1000);
        Page<AnalysisManageDTO> managePage = manageService.getForPage(manageQuery);
        model.addAttribute("managePage", managePage);
    }

    /**
     * 获取会员列表
     *
     * @param model model
     */
    public void getUserPage(Model model) {
        TransportUserDTOQuery userQuery = new TransportUserDTOQuery();
        userQuery.setStopFlag(0);
        userQuery.setPageSize(10000);
        Page<TransportUserDTO> userPage = userService.getForPage(userQuery);
        model.addAttribute("userPage", userPage);
    }

    /**
     * 只获取管理员、司机的会员列表
     *
     * @param model model
     */
    public void getManageDriverUser(Model model) {
        model.addAttribute("userPage", userService.getManageDriverUser(null, null));
    }

    /**
     * 获取分类列表
     *
     * @param model     model
     * @param modelType CatalogTypeEnum枚举
     * @return 分类列表
     */
    public Model getCatalogPage(Model model, Integer modelType) {
        return getCatalogPage(model, modelType, "");
    }

    /**
     * 获取分类列表（自定义映射名称）
     *
     * @param model     model
     * @param modelType 类型
     * @param attrName  映射名称
     * @return 分类列表
     */
    public Model getCatalogPage(Model model, Integer modelType, String attrName) {
        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setModelType(modelType);
        query.setStopFlag(0);
        query.setPageSize(1000);
        Page<AnalysisVisualCatalogDTO> list = catalogService.getForPage(query);

        if (list != null) { //上面限制获取1000条记录，因此要使用这种递归方式
            if (StringUtils.isBlank(attrName)) {
                attrName = "catalogList";
            }
            model.addAttribute(attrName, catalogService.getListByRecursion(list.getItems(), 0, "|"));
        }

        return model;
    }

    /**
     * 获取分类列表（递归）
     *
     * @param model     model
     * @param modelType 类型
     * @param attrName  映射名称
     */
    public void getCatalogListForRecursion(Model model, Integer modelType, String attrName) {
        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setModelType(modelType);
        query.setStopFlag(0);
        query.setPageSize(1000);
        Page<AnalysisVisualCatalogDTO> list = catalogService.getForPage(query);
        if (list != null) { //上面限制获取1000条记录，因此要使用这种递归方式
            model.addAttribute(attrName, catalogService.getListByRecursion(list.getItems(), 0, "|"));
        }
    }

    /**
     * 获取公司列表
     *
     * @param model model
     * @return 公司列表
     */
    public Model getCompayPage(Model model, Integer companyType) {
        return getCompayPage(model, companyType, null, null);
    }

    /**
     * 获取公司列表（自定义映射名称）
     *
     * @param model model
     * @return 公司列表
     */
    public Model getCompayPage(Model model, Integer companyType, Integer parentId, String attrName) {
        TransportCompanyDTOQuery query_company = new TransportCompanyDTOQuery();
        if (parentId != null) {
            query_company.setParentId(parentId);
        }
        query_company.setCompanyType(companyType);
        query_company.setStopFlag(0);
        query_company.setPageSize(1000);
        Page<TransportCompanyDTO> companyPage = companyService.getForPage(query_company);

        if (companyPage != null) { //上面限制获取1000条记录，因此要使用这种递归方式
            if (StringUtils.isBlank(attrName)) {
                attrName = "companyList";
            }

            if (parentId != null && parentId > 0) {
                model.addAttribute(attrName, companyService.getChildrenForEach(companyPage.getItems(), "|"));
            } else {
                model.addAttribute(attrName, companyService.getListByRecursion(companyPage.getItems(), 0, "|"));
            }
        }

        return model;
    }

    /**
     * 获取中英文对照表
     *
     * @param model model
     */
    public void getChineseEnglishPage(Model model) {
        TransportTableChineseEnglishDTOQuery englishQuery = new TransportTableChineseEnglishDTOQuery();
        englishQuery.setStopFlag(0);
        englishQuery.setPageSize(1000);
        Page<TransportTableChineseEnglishDTO> englishPage = englishService.getForPage(englishQuery);
        model.addAttribute("englishPage", englishPage);
    }

    /**
     * 获取全国行政区列表
     *
     * @param model model
     * @return 全国行政区列表
     */
    public Model getRegionPage(Model model, Integer parentId) {
        return getRegionPage(model, parentId, null);
    }

    /**
     * 获取全国行政区列表（自定义映射名称）
     *
     * @param model model
     * @return 全国行政区列表
     */
    public Model getRegionPage(Model model, Integer parentId, String attrName) {
        if (parentId == null) parentId = 0;

        AnalysisRegionDTOQuery query_region = new AnalysisRegionDTOQuery();
        query_region.setParentId(parentId);
        query_region.setPageSize(1000);
        Page<AnalysisRegionDTO> regionPage = regionService.getForPage(query_region);

        if (StringUtils.isBlank(attrName)) {
            attrName = "regionPage";
        }
        model.addAttribute(attrName, regionPage);

        return model;
    }

    /**
     * 获取用户区域表
     *
     * @param model model
     * @return 用户区域表
     */
    public Model getIotRegionPage(Model model) {
        IotRegionDTOQuery regionQuery = new IotRegionDTOQuery();
        regionQuery.setParentId(0);
        regionQuery.setStopFlag(0);
        regionQuery.setPageSize(1000);
        Page<IotRegionDTO> regionPage = iotRegionService.getForPage(regionQuery);
        List<IotRegionDTO> regionList = iotRegionService.getChildrenForEach(regionPage.getItems(), "|");

        model.addAttribute("regionList", regionList);

        return model;
    }

    /**
     * 获取已上传文件列表
     *
     * @param model   model
     * @param fileIds 已上传文件ID
     */
    public void getUploadPage(Model model, String fileIds) {
        if (StringUtils.isBlank(fileIds)) {
            return;
        }

        TransportUploadFilesDTOQuery query = new TransportUploadFilesDTOQuery();
        query.setIds(FormatUtils.commaToList_Integer(fileIds));
        query.setStopFlag(0);
        query.setOrderBy("order by id desc");
        Page<TransportUploadFilesDTO> dataPage = uploadFilesService.getForPage(query);
        for (TransportUploadFilesDTO item : dataPage.getItems()) {
            String pic = GeneralUtils.getContentTypeUrl(item.getContentType());
            if (StringUtils.isBlank(pic)) {
                pic = item.getWebUrl();
            }
            item.setIconUrl(pic);
        }
        model.addAttribute("uploadFilePage", dataPage);
    }

    /**
     * 获取MES系统设备列表
     *
     * @param model model
     */
    public void getMesEquipmentPage(Model model) {
        MesEquipmentDTOQuery equipQuery = new MesEquipmentDTOQuery();
        equipQuery.setStopFlag(0);
        equipQuery.setPageSize(1000);
        equipQuery.setOrderBy("order by id desc");
        Page<MesEquipmentDTO> equipmentPage = mesEquipmentService.getForPage(equipQuery);

        model.addAttribute("equipmentPage", equipmentPage);
    }

    /**
     * 获取MES产品列表
     *
     * @param model model
     */
    public void getMesProductPage(Model model) {
        MesProductDTOQuery productQuery = new MesProductDTOQuery();
        productQuery.setParentId(0);
        productQuery.setStopFlag(0);
        productQuery.setPageSize(1000);
        productQuery.setOrderBy("order by id desc");
        Page<MesProductDTO> productPage = mesProductService.getForPage(productQuery);

        //规格型号
        MesProductDTOQuery childQuery;
        Page<MesProductDTO> childPage;

        //新列表
        List<MesProductDTO> newProductList = new ArrayList<>();

        for (MesProductDTO item : productPage.getItems()) {
            //获取规格型号
            childQuery = new MesProductDTOQuery();
            childQuery.setParentId(item.getId());
            childQuery.setStopFlag(0);
            childQuery.setOrderBy("order by id desc");
            childPage = mesProductService.getForPage(childQuery);
            for (MesProductDTO ci : childPage.getItems()) {
                ci.setProductName(item.getProductName());
                ci.setProductCode(item.getProductCode());
                ci.setChipName(item.getChipName());

                newProductList.add(ci);
            }
        }

        model.addAttribute("productList", newProductList);
    }

    /**
     * 获取MES生产工艺
     *
     * @param model model
     */
    public void getMesWorkmanship(Model model) {
        MesProduceWorkmanshipDTOQuery query = new MesProduceWorkmanshipDTOQuery();
        query.setStopFlag(0);
        query.setPageSize(1000);
        query.setOrderBy("order by id desc");
        Page<MesProduceWorkmanshipDTO> dataPage = mesProduceWorkmanshipService.getForPage(query);
        model.addAttribute("workmanshipPage", dataPage);
    }

    /**
     * 获取MES生产线
     *
     * @param model model
     */
    public void getMesProduceLine(Model model) {
        MesProduceLineDTOQuery query = new MesProduceLineDTOQuery();
        query.setStopFlag(0);
        query.setPageSize(1000);
        query.setOrderBy("order by id desc");
        Page<MesProduceLineDTO> dataPage = mesProduceLineService.getForPage(query);
        model.addAttribute("produceLinePage", dataPage);
    }

    //endregion

    //region 名称工具

    /**
     * 根据用户pin获取当前用户的企业ID
     *
     * @param pin 用户pin
     * @return 企业ID
     */
    public Integer getCurrentEnterprise(HttpServletResponse response, String pin) {
        int entId = -1;
        try {
            entId = jedisCache.get(KeyConstants.WEBSITE_CURRENT_ENTERPRISE_ID + pin, -1);

            if (entId <= 0) {
                //首页会判断是需要选择企业还是要重新登录
                response.sendRedirect("/");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return entId;
    }

    /**
     * 根据用户pin获取当前用户的企业ID
     * （只在登录时使用）
     *
     * @param pin 用户pin
     * @return 企业ID
     */
    public Integer getUserMainEnterprise(String pin) {
        Integer entId = jedisCache.get(KeyConstants.WEBSITE_CURRENT_ENTERPRISE_ID + pin, -1);
        if (entId > 0) {
            return entId;
        }

        AnalysisManageDTO user = manageService.getFromCachePin(pin);
        if (user != null) {
            List<Integer> entids = enterpriseRelService.getEnterpriseIdByManage(user.getId());
            if (entids.size() > 0) {
                entId = entids.get(0);
            }
        }

        return entId;
    }

    /**
     * 获取部门名称
     *
     * @param depId 部门ID
     * @return 部门名称
     */
    public String getDepName(Integer depId) {
        if (depId == null || depId <= 0) {
            return null;
        }

        TransportDepartmentDTO depDTO = departmentService.getFromCacheId(depId);
        return depDTO == null ? "--" : depDTO.getDepNameCn();
    }

    /**
     * 获取角色名称
     *
     * @param roleId 角色ID
     * @return 角色名称
     */
    public String getRoleName(Integer roleId) {
        if (roleId == null || roleId <= 0) {
            return null;
        }

        TransportRolesDTO roleDTO = rolesService.getFromCacheId(roleId);
        return roleDTO == null ? "--" : roleDTO.getRoleNameCn();
    }

    /**
     * 获取管理员名称
     *
     * @param manageId 管理员id
     * @return 管理员
     */
    public String getManageName(Integer manageId) {
        if (manageId == null || manageId <= 0) {
            return null;
        }
        AnalysisManageDTO manageDTO = manageService.getFromCacheId(manageId);
        return manageDTO == null ? "--" : manageDTO.getNickName();
    }

    /**
     * 获取分类名称
     *
     * @param cateId 分类id
     * @return 分类名称
     */
    public String getCatalogName(Integer cateId) {
        if (cateId == null || cateId <= 0) {
            return null;
        }
        AnalysisVisualCatalogDTO catalogDTO = catalogService.getFromCacheId(cateId);
        return catalogDTO == null ? "--" : catalogDTO.getCatalogName();
    }

    /**
     * 获取分类名称（英文）
     *
     * @param cateId 分类id
     * @return 分类名称
     */
    public String getCatalogNameEn(Integer cateId) {
        if (cateId == null || cateId <= 0) {
            return null;
        }
        AnalysisVisualCatalogDTO catalogDTO = catalogService.getFromCacheId(cateId);
        return catalogDTO == null ? "--" : catalogDTO.getCatalogNameEn();
    }

    /**
     * 获取分类名称（通过分类编码）
     *
     * @param cateCode 分类编码
     * @return 分类名称
     */
    public String getCatalogNameByEn(String cateCode) {
        if (StringUtils.isBlank(cateCode)) {
            return null;
        }
        AnalysisVisualCatalogDTO catalogDTO = catalogService.getByCateEnName(cateCode);
        return catalogDTO == null ? "--" : catalogDTO.getCatalogName();
    }

    /**
     * 获取公司名称
     *
     * @param companyuId 公司id
     * @return 公司名称
     */
    public String getCompanyName(Integer companyuId) {
        if (companyuId == null || companyuId <= 0) {
            return null;
        }
        TransportCompanyDTO companyDTO = companyService.getFromCacheId(companyuId);
        return companyDTO == null ? "--" : companyDTO.getCompanyNameCn();
    }

    /**
     * 获取会员姓名
     *
     * @param userId 会员id
     * @return 会员姓名
     */
    public String getUserTrueName(Integer userId) {
        if (userId == null || userId <= 0) {
            return null;
        }
        TransportUserDTO userDTO = userService.getFromCacheId(userId);
        return userDTO == null ? "--" : userDTO.getTrueName();
    }

    /**
     * 获取会员姓名
     *
     * @param adminId 管理员id
     * @return 会员姓名
     */
    public String getUserTrueNameByAdminId(Integer adminId) {
        if (adminId == null || adminId <= 0) {
            return null;
        }

        TransportUserDTO user = userService.getByRelId(adminId, UserTypeEnum.MANAGE.getKey());
        return user == null ? "--" : user.getTrueName();
    }

    /**
     * 获取中文对照名称
     *
     * @param tableId 数据表id
     * @return 表名称
     */
    public String getChineseName(Integer tableId) {
        if (tableId == null || tableId <= 0) {
            return null;
        }
        TransportTableChineseEnglishDTO englishDTO = englishService.getById(tableId);
        return englishDTO == null ? "--" : englishDTO.getTableNameCn();
    }

    /**
     * 获取物料名称
     *
     * @param purchaseId 物料id
     * @return 物料名称
     */
    public String getPurchaseName(Integer purchaseId) {
        if (purchaseId == null || purchaseId <= 0) {
            return null;
        }
        TransportPurchaseDTO purchaseDTO = purchaseService.getFromCacheId(purchaseId);
        return purchaseDTO == null ? "--" : purchaseDTO.getPartName();
    }

    /**
     * 获取行政区名称
     * 全国行政区划数据（省、市、县(区)、镇(街道)、村）
     *
     * @param regionId id
     * @return 行政区名称
     */
    public String getRegionName(Integer regionId) {
        if (regionId == null || regionId <= 0) {
            return null;
        }
        AnalysisRegionDTO regionDTO = regionService.getFromCacheId(regionId);
        return regionDTO == null ? "--" : regionDTO.getRegionName();
    }

    /**
     * 获取用户区域名称
     *
     * @param areaId 用户区域id
     * @return 用户区域名称（区域-楼宇-单元）
     */
    public String getIotRegionName(Integer areaId) {
        if (areaId == null || areaId <= 0) {
            return null;
        }
        IotRegionDTO regionDTO = iotRegionService.getFromCacheId(areaId);
        if (regionDTO == null) {
            return "--";
        }

        String regionName = regionDTO.getArea();
        if (StringUtils.isNotBlank(regionDTO.getBuilding())) {
            regionName += "-" + regionDTO.getBuilding();
        }
        if (StringUtils.isNotBlank(regionDTO.getUnit())) {
            regionName += "-" + regionDTO.getUnit();
        }

        return regionName;
    }

    /**
     * 获取用户区域名称
     *
     * @param areaId 用户区域id
     * @return 用户区域名称（区域-楼宇-单元）
     */
    public String getIotRegionUnit(Integer areaId) {
        if (areaId == null || areaId <= 0) {
            return null;
        }
        IotRegionDTO regionDTO = iotRegionService.getFromCacheId(areaId);
        if (regionDTO == null) {
            return "--";
        }

        String regionName = regionDTO.getBuilding();
        if (StringUtils.isNotBlank(regionDTO.getUnit())) {
            regionName += "-" + regionDTO.getUnit();
        }

        return regionName;
    }

    /**
     * 获取用户区域名称
     *
     * @param areaId 用户区域id
     * @return 用户区域名称（楼宇）
     */
    public String getIotRegionBuilding(Integer areaId) {
        if (areaId == null || areaId <= 0) {
            return null;
        }
        IotRegionDTO regionDTO = iotRegionService.getFromCacheId(areaId);
        return regionDTO == null ? "--" : regionDTO.getBuilding();
    }

    /**
     * 获取MES系统设备名称
     *
     * @param equipId 设备id
     * @return 设备名称
     */
    public String getMesEquipName(Integer equipId) {
        if (equipId == null || equipId <= 0) {
            return "--";
        }
        MesEquipmentDTO equipmentDTO = mesEquipmentService.getFromCacheId(equipId);
        return equipmentDTO == null ? "--" : equipmentDTO.getEquipName();
    }

    /**
     * 获取MES产品名称
     *
     * @param productId 产品id
     * @return 产品名称
     */
    public String getMesProductName(Integer productId) {
        if (productId == null || productId <= 0) {
            return "--";
        }
        MesProductDTO productDTO = mesProductService.getFromCacheId(productId);
        return productDTO == null ? "--" : productDTO.getProductName();
    }

    /**
     * 获取MES工艺名称
     *
     * @param shipId 工艺id
     * @return 工艺名称
     */
    public String getMesShipName(Integer shipId) {
        if (shipId == null || shipId <= 0) {
            return "--";
        }
        MesProduceWorkmanshipDTO shipDTO = mesProduceWorkmanshipService.getFromCacheId(shipId);
        return shipDTO == null ? "--" : shipDTO.getShipName();
    }

    /**
     * 获取MES工序名称
     *
     * @param processId 工序ID
     * @return 工序名称
     */
    public String getMesProcessName(Integer processId) {
        if (processId == null || processId <= 0) {
            return "--";
        }
        MesProduceWorkmanshipProcessDTO processDTO = mesProduceWorkmanshipProcessService.getFromCacheId(processId);
        return processDTO == null ? "--" : processDTO.getProcessName();
    }

    /**
     * 获取MES生产线名称
     *
     * @param lineId 生产线id
     * @return 生产线名称
     */
    public String getMesProduceLineName(Integer lineId) {
        if (lineId == null || lineId <= 0) {
            return "--";
        }
        MesProduceLineDTO lineDTO = mesProduceLineService.getFromCacheId(lineId);
        return lineDTO == null ? "--" : lineDTO.getLineName();
    }

    //endregion

    //region 独立权限

    /**
     * 权限：超级权限（管理员）
     *
     * @param model model
     * @param pin   用户pin
     */
    public void getSupperAuthor(Model model, String pin) {
        int canExec = 0;
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        }
        model.addAttribute("supperAuthor", canExec);
    }

    /**
     * 权限：订单打印
     *
     * @param model model
     * @param pin   用户pin
     */
    public void getPrintOrderAuthor(Model model, String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("dayindingdan", curr_obj.getId());
        }
        model.addAttribute("printOrderExec", canExec);
    }

    /**
     * 权限：导出手机
     *
     * @param model model
     * @param pin   用户pin
     */
    public void getExportMobileAuthor(Model model, String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("daochushouji", curr_obj.getId());
        }
        model.addAttribute("exportMobileExec", canExec);
    }

    /**
     * 权限：导出订单
     *
     * @param model model
     * @param pin   用户pin
     */
    public void getExportOrderAuthor(Model model, String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("daochudingdan", curr_obj.getId());
        }
        model.addAttribute("exportOrderExec", canExec);
    }

    /**
     * 权限：查看全部数据
     *
     * @param pin 用户pin
     * @return 权限ID
     */
    public Integer getLookAlldataAuthor(String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("quanbushuju", curr_obj.getId());
        }
        return canExec;
    }

    /**
     * 权限：查看全部任务
     *
     * @param pin 用户pin
     * @return 权限ID
     */
    public Integer getLookAllTaskAuthor(String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("quanburenwu", curr_obj.getId());
        }
        return canExec;
    }

    /**
     * 权限：审批
     *
     * @param pin 用户pin
     * @return 权限ID
     */
    public Integer getLookAllApprovalAuthor(String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("shenpiquanxian", curr_obj.getId());
        }
        return canExec;
    }

    /**
     * 权限：位置隐私
     *
     * @param pin 用户pin
     * @return 权限ID
     */
    public Integer getLookAllPrivacyAuthor(String pin) {
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer canExec = 0;
        if (curr_obj.getIsSuper() == 1) {
            canExec = 1;
        } else {
            canExec = manageRightRoleService.getRoleAdminRel("weizhiyinsi", curr_obj.getId());
        }
        return canExec;
    }

    //endregion

    //region 日期工具

    /**
     * 获取年月日
     *
     * @param model model
     * @return 年月日
     */
    public Model getDateTool(Model model, Integer currYear, Integer currMonth) {
        return getDateTool(model, currYear, currMonth, 0, 0);
    }

    /**
     * 获取年月日列表
     *
     * @param model     model
     * @param currYear  当前年
     * @param currMonth 当前月
     * @param zeroMonth 月份中是否包含0
     * @param zeroDay   天数中是否包含0
     * @return 年月日
     */
    public Model getDateTool(Model model, Integer currYear, Integer currMonth, Integer zeroMonth, Integer zeroDay) {
        //年
        List<Integer> yearList = new ArrayList<>();
        for (int i = 2015; i <= 2049; i++) {
            yearList.add(i);
        }
        model.addAttribute("yearList", yearList);

        //月
        List<Integer> monthList = new ArrayList<>();
        if (zeroMonth == 1) {
            monthList.add(0);
        }
        for (int i = 1; i <= 12; i++) {
            monthList.add(i);
        }
        model.addAttribute("monthList", monthList);

        //日
        List<Integer> dayList = new ArrayList<>();
        if (zeroDay == 1) {
            dayList.add(0);
        }

        int j = 31;
        if (currMonth == 2) {
            if (currYear % 4 == 0) {
                j = 29;
            } else {
                j = 28;
            }
        }
        if (currMonth == 4 || currMonth == 6 || currMonth == 9 || currMonth == 11) {
            j = 30;
        }

        for (int i = 1; i <= j; i++) {
            dayList.add(i);
        }
        model.addAttribute("dayList", dayList);

        return model;
    }

    /**
     * 获取日列表
     *
     * @param model     model
     * @param currMonth 当前月，空代表当前月
     * @param zeroDay   天数中是否包含0
     */
    public void getDayListTool(Model model, Integer currMonth, Integer zeroDay) {

        List<Integer> dayList = new ArrayList<>();
        if (zeroDay == 1) {
            dayList.add(0);
        }

        Calendar rightNow = Calendar.getInstance();
        int currYear = rightNow.get(Calendar.YEAR);

        if (currMonth == null || currMonth <= 0) {
            currMonth = rightNow.get(Calendar.MONTH) + 1;
        }

        int j = 31;
        if (currMonth == 2) {
            if (currYear % 4 == 0) {
                j = 29;
            } else {
                j = 28;
            }
        }
        if (currMonth == 4 || currMonth == 6 || currMonth == 9 || currMonth == 11) {
            j = 30;
        }

        for (int i = 1; i <= j; i++) {
            dayList.add(i);
        }
        model.addAttribute("dayList", dayList);
    }
    //endregion

    //region ID 转换

    /**
     * 通过会员ID获取管理员ID
     *
     * @param userId 会员ID
     * @return id
     */
    public Integer getAdminIdByUserId(Integer userId) {
        Integer adminId = 0;

        TransportUserDTO user = userService.getFromCacheId(userId);
        if (user != null) {
            adminId = user.getManageId();
        }

        return adminId;
    }

    /**
     * 通过会员ID获取司机ID
     *
     * @param userId 会员ID
     * @return id
     */
    public Integer getDriverIdByUserId(Integer userId) {
        Integer driverId = 0;

        TransportUserDTO user = userService.getFromCacheId(userId);
        if (user != null) {
            driverId = user.getDriverId();
        }

        return driverId;
    }

    /**
     * 通过管理员ID获取会员ID
     *
     * @param adminId 管理员ID
     * @return id
     */
    public Integer getUserIdByAdminId(Integer adminId) {
        Integer userId = 0;

        TransportUserDTO user = userService.getByRelId(adminId, UserTypeEnum.MANAGE.getKey());
        if (user != null) {
            userId = user.getId();
        }

        return userId;
    }

    /**
     * 通过司机ID获取会员ID
     *
     * @param driverId 司机ID
     * @return 会员ID
     */
    public Integer getUserIdByDriverId(Integer driverId) {
        Integer userId = 0;

        TransportUserDTO user = userService.getByRelId(driverId, UserTypeEnum.DRIVER.getKey());
        if (user != null) {
            userId = user.getId();
        }

        return userId;
    }

    /**
     * 通过员工ID获取会员ID
     *
     * @param staffId 员工ID
     * @return 会员ID
     */
    public Integer getUserIdByStaffId(Integer staffId) {
        Integer userId = 0;

        TransportUserDTO user = userService.getByRelId(staffId, UserTypeEnum.STAFF.getKey());
        if (user != null) {
            userId = user.getId();
        }

        return userId;
    }

    //endregion

    //region 搜索用，补全用户ID，司机ID，车辆ID

    /**
     * 补全用户ID
     *
     * @param userId       用户ID，优先级1；如果用户名不存在，则返回默认值
     * @param userName     用户姓名，用户ID不存在时，拿用户名去取
     * @param defaultValue 默认值
     * @return 新userid
     */
    public Integer completionUserId(Integer userId, String userName, Integer defaultValue) {
        //用户没有搜索或取消了搜索
        if (StringUtils.isBlank(userName)) {
            return defaultValue;
        }

        //第一优先级
        if (userId != null && userId > 0) {
            return userId;
        }

        //通过用户名获取
        TransportUserDTO user = userService.getByTrueName(userName);
        if (user != null) {
            return user.getId();
        }

        return defaultValue;
    }

    //endregion
}
